{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# LlamaIndex + Strata Integration\n",
        "\n",
        "This tutorial demonstrates how to build AI agents using LlamaIndex with Klavis Strata MCP servers for enhanced functionality.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Prerequisites\n",
        "\n",
        "Before we begin, you'll need:\n",
        "\n",
        "- **OpenAI API key** - Get at [openai.com](https://openai.com/)\n",
        "- **Klavis API key** - Get at [klavis.ai](https://klavis.ai/)\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\n",
            "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m25.1.1\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m25.2\u001b[0m\n",
            "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpip install --upgrade pip\u001b[0m\n",
            "Note: you may need to restart the kernel to use updated packages.\n"
          ]
        }
      ],
      "source": [
        "# Install the required packages\n",
        "%pip install -q klavis python-dotenv llama-index-llms-openai llama-index-tools-mcp llama-index-core\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "\n",
        "import os\n",
        "import webbrowser\n",
        "from klavis import Klavis\n",
        "from klavis.types import McpServerName\n",
        "from llama_index.llms.openai import OpenAI\n",
        "from llama_index.core.agent.workflow import FunctionAgent\n",
        "from llama_index.tools.mcp import BasicMCPClient, aget_tools_from_mcp_url\n",
        "\n",
        "# Set environment variables\n",
        "os.environ[\"OPENAI_API_KEY\"] = \"YOUR_OPENAI_API_KEY\"  # Replace with your actual OpenAI API key\n",
        "os.environ[\"KLAVIS_API_KEY\"] = \"YOUR_KLAVIS_API_KEY\"  # Replace with your actual Klavis API key"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Step 1: Create Strata MCP Server\n",
        "\n",
        "Create a unified MCP server that combines multiple services (Gmail and YouTube) for enhanced agent capabilities.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 9,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "🚀 Strata MCP server created successfully!\n",
            "🔐 Opening OAuth authorization for Gmail\n"
          ]
        }
      ],
      "source": [
        "klavis_client = Klavis(api_key=os.getenv(\"KLAVIS_API_KEY\"))\n",
        "\n",
        "# Create a Strata MCP server with Gmail and YouTube integrations\n",
        "response = klavis_client.mcp_server.create_strata_server(\n",
        "    user_id=\"1234\",\n",
        "    servers=[McpServerName.GMAIL, McpServerName.YOUTUBE],\n",
        ")\n",
        "\n",
        "print(f\"🚀 Strata MCP server created successfully!\")\n",
        "\n",
        "# Handle OAuth authorization if needed\n",
        "if response.oauth_urls:\n",
        "    for server_name, oauth_url in response.oauth_urls.items():\n",
        "        webbrowser.open(oauth_url)\n",
        "        print(f\"🔐 Opening OAuth authorization for {server_name}\")\n",
        "        input(f\"Press Enter after completing {server_name} OAuth authorization...\")\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Step 2: Create LlamaIndex Agent with MCP Tools\n",
        "\n",
        "Set up the LlamaIndex FunctionAgent with tools from the Strata MCP server.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 15,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "🤖 LlamaIndex agent created with MCP tools!\n"
          ]
        }
      ],
      "source": [
        "# Get all available tools from Strata\n",
        "tools = await aget_tools_from_mcp_url(\n",
        "    response.strata_server_url, \n",
        "    client=BasicMCPClient(response.strata_server_url)\n",
        ")\n",
        "\n",
        "# Setup LLM\n",
        "llm = OpenAI(model=\"gpt-4o-mini\", api_key=os.getenv(\"OPENAI_API_KEY\"))\n",
        "\n",
        "# Create LlamaIndex agent with MCP tools\n",
        "agent = FunctionAgent(\n",
        "    name=\"my_first_agent\",\n",
        "    description=\"Agent using MCP-based tools\",\n",
        "    tools=tools,\n",
        "    llm=llm,\n",
        "    system_prompt=\"You are an AI assistant that uses MCP tools.\",\n",
        ")\n",
        "\n",
        "print(\"🤖 LlamaIndex agent created with MCP tools!\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Step 3: Run the Agent\n",
        "\n",
        "Use the agent to summarize a YouTube video and send the summary via email.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 16,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "✅ Result:\n",
            "### Video Summary\n",
            "The video titled **“Golden” Official Lyric Video | KPop Demon Hunters | Sony Animation** features the official lyric video for the song \"Golden\" from the KPop Demon Hunters soundtrack. The KPop Demon Hunters series is available on Netflix and follows KPop superstars Rumi, Mira, and Zoey, who lead double lives as demon hunters protecting their fans from supernatural threats. The video showcases vibrant animations and catchy lyrics, appealing to fans of K-Pop and animation alike.\n",
            "\n",
            "**Key Details:**\n",
            "- **Published At:** June 23, 2025\n",
            "- **Channel:** Sony Pictures Animation\n",
            "- **Duration:** 3 minutes and 19 seconds\n",
            "- **View Count:** 372,127,057\n",
            "- **Like Count:** 2,861,033\n",
            "- **Comment Count:** 87,798\n",
            "- **Watch Here:** [Golden - KPop Demon Hunters](https://www.youtube.com/watch?v=yebNIHKAC4A)\n",
            "\n",
            "### Email Sent\n",
            "The summary has been successfully sent to your email at **your-email@example.com**.\n"
          ]
        }
      ],
      "source": [
        "# Configure your preferences\n",
        "my_email = \"your-email@example.com\"  # Replace with your email\n",
        "youtube_video_url = \"https://youtu.be/yebNIHKAC4A?si=1Rz_ZsiVRz0YfOR7\"  # Replace with your favorite video\n",
        "\n",
        "# Invoke the agent\n",
        "response = await agent.run(\n",
        "    f\"summarize this video - {youtube_video_url} and mail this summary to my email {my_email}\"\n",
        ")\n",
        "\n",
        "print(\"✅ Result:\")\n",
        "print(response)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Summary\n",
        "\n",
        "🎉 Congratulations! You've successfully created a LlamaIndex agent that can:\n",
        "\n",
        "1. **Summarize YouTube videos** using the YouTube MCP server\n",
        "2. **Send emails** using the Gmail MCP server\n",
        "3. **Coordinate multiple services** through Klavis Strata MCP integration\n",
        "\n",
        "This demonstrates the power of combining LlamaIndex's FunctionAgent with Klavis MCP servers for building sophisticated AI workflows that can interact with multiple external services seamlessly.\n"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": ".venv",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.13.5"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 2
}
